package com.gengzi.lot.item.service;

import com.gengzi.lot.item.mapper.MenuMapper;
import com.gengzi.lot.item.pojo.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class MenuService {

    @Autowired
    private MenuMapper menuMapper;

    public List<Menu> querymenuListByPid(Long pid) {
        Menu menu = new Menu();
        menu.setParentId(pid);
        return this.menuMapper.select(menu);
    }

    public List<Menu> getList() {
        return this.menuMapper.selectAll();
    }

    public List<Menu> getTree() {
        List<Menu> list = getList();
        List<Menu> result = new ArrayList<>();
        list.forEach(item->{
            if (item.getParentId() == 0L){
                result.add(tree(item,list));
            }
        });
        return result;
    }

    private static Menu tree(Menu menu, List<Menu> list){
        menu.setChildren(new ArrayList<>());
        list.forEach(item->{
            if(menu.getId().equals(item.getParentId())) {
                if (menu.getChildren() == null) {
                    menu.setChildren(new ArrayList<>());
                }
                menu.getChildren().add(tree(item, list));
            }
        });
        return menu;
    }
}
